package vn.scopionstudio.lockappandorid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import vn.scopionstudio.lockappandorid.broadcast.UnInstallReceiver;
import vn.scopionstudio.lockappandorid.database.DBApp;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckedTextView;
import android.widget.ListView;

public class LockMain extends Activity implements OnItemClickListener {

		   /* whether or not to include system apps */
		   private static final boolean INCLUDE_SYSTEM_APPS = false;
		   
		   private ListView mAppsList;
		   private AppListAdapter mAdapter;
		   private List<App> mApps;
		   Timer timer;
		   ActivityManager activityManager;
		   private DBApp mdb;
		   UnInstallReceiver receiver;
		   /** Called when the activity is first created. */
		   @Override
		   public void onCreate(Bundle savedInstanceState) {
		      super.onCreate(savedInstanceState);
		      setContentView(R.layout.activity_lock_main);
		      mdb=new DBApp(getBaseContext());
		      Intent i = new Intent(this,AppLaunchCheckService.class);
				this.startService(i);
		      mAppsList = (ListView) findViewById(R.id.appslist);
		      mAppsList.setOnItemClickListener(this);
		   
		      mApps = loadInstalledApps(INCLUDE_SYSTEM_APPS);
		      
		      mAdapter = new AppListAdapter(getApplicationContext());
		      mAdapter.setListItems(mApps);
		      mAppsList.setAdapter(mAdapter);
		      new LoadIconsTask().execute(mApps.toArray(new App[]{}));
		     
		   }
		   
		   @Override
		   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			   
		      final App app = (App) parent.getItemAtPosition(position);
		     
		      mAdapter.check = false;
				CheckedTextView tvSubject = (CheckedTextView)view
						.findViewById(R.id.tvSubject);
				
				
				if (!(tvSubject.isChecked())) {
					Log.e("Te: ", "insert");
					 mdb.AddApp(app.getPackageName());
					tvSubject.setChecked(true);
					
					
				} else {
					Log.e("Te: ", "delete");
					 mdb.deleteUser(app.getPackageName());
					tvSubject.setChecked(false);
				}
				
				CheckAppDB();
				save(position, tvSubject.isChecked());
				
				
		   }
		   public void CheckAppDB(){
			   ArrayList<String> listPackageName = mdb.GetApp();
			   if(listPackageName.size()>0){
				   for(int i=0;i<listPackageName.size();i++){
					   Log.e("Lock Main: ", listPackageName.get(i));
				   }
				   
			   }
			   
		   }
		   
		   /**
		    * Uses the package manager to query for all currently installed apps which are put into beans and returned
		    * in form of a list.
		    * 
		    * @param includeSysApps whether or not to include system applications
		    * @return a list containing an {@code App} bean for each installed application 
		    */
		   private List<App> loadInstalledApps(boolean includeSysApps) {
		      List<App> apps = new ArrayList<App>();
		      
		      // the package manager contains the information about all installed apps
		      PackageManager packageManager = getPackageManager();
		      
		      List<PackageInfo> packs = packageManager.getInstalledPackages(0); //PackageManager.GET_META_DATA 
		      
		      for(int i=0; i < packs.size(); i++) {
		         PackageInfo p = packs.get(i);
		         ApplicationInfo a = p.applicationInfo;
		         // skip system apps if they shall not be included
		         if ((!includeSysApps) && ((a.flags & ApplicationInfo.FLAG_SYSTEM) == 1)) {
		            continue;
		         }
		         App app = new App();
		         app.setTitle(p.applicationInfo.loadLabel(packageManager).toString());
		         app.setPackageName(p.packageName);
		         app.setVersionName(p.versionName);
		         app.setVersionCode(p.versionCode);
		         CharSequence description = p.applicationInfo.loadDescription(packageManager);
		         app.setDescription(description != null ? description.toString() : "");
		         apps.add(app);
		      }
		      return apps;
		   }
		   
		   /**
		    * An asynchronous task to load the icons of the installed applications.
		    */
		   private class LoadIconsTask extends AsyncTask<App, Void, Void> {
		      @Override
		      protected Void doInBackground(App... apps) {
		         
		         Map<String, Drawable> icons = new HashMap<String, Drawable>();
		         PackageManager manager = getApplicationContext().getPackageManager();
		         
		         for (App app : apps) {
		            String pkgName = app.getPackageName();
		            Drawable ico = null;
		            try {
		               Intent i = manager.getLaunchIntentForPackage(pkgName);
		               if (i != null) {
		                  ico = manager.getActivityIcon(i);
		               }
		            } catch (NameNotFoundException e) {
		               Log.e("ERROR", "Unable to find icon for package '" + pkgName + "': " + e.getMessage());
		            }
		            icons.put(app.getPackageName(), ico);
		         }
		         mAdapter.setIcons(icons);
		         
		         return null;
		      }
		      
		      @Override
		      protected void onPostExecute(Void result) {
		         mAdapter.notifyDataSetChanged();
		      }
		  }
		   private void save(int index, boolean isChecked) {
			    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
			   SharedPreferences.Editor editor = sharedPreferences.edit();
			    editor.putBoolean("check" + index, isChecked);
			    editor.commit();
			}
			@Override
			protected void onPause() {
			// TODO Auto-generated method stub
			super.onPause();
			//unregisterReceiver(receiver);
			}

		}
